import { BadRequestException, Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Throttle } from '@nestjs/throttler';
import { createTransport, Transporter } from 'nodemailer';
import { randomBetween } from 'src/utils';

@Injectable()
export class EmailService {
  transporter: Transporter;
  transporterPool: { transporter: Transporter; user: string; useCount: number }[] = [];

  constructor() {
    const emails = [
      {
        host: 'smtp.qq.com',
        port: 587,
        users: [
          { user: '1730821420@qq.com', pass: 'cuhmymtxfkoiefii' },
          { user: '2879853856@qq.com', pass: 'gleygkxlisdbdhaf' },
          { user: '1481460248@qq.com', pass: 'gexagpqhvbzxgjbj' },
          { user: '3597572537@qq.com', pass: 'kqofpwktzmficjad' },
        ],
      },
      {
        host: 'smtp.163.com',
        port: 25,
        users: [
          { user: '15360001247@163.com', pass: 'VYmBVGhYWPeeuyVB' },
          { user: '15975526840@163.com', pass: 'AWvNAPCfHpAqTncR' },
          { user: '15817968467@163.com', pass: 'DNvVypjAXyQ9BJVX' },
          { user: '19872791470@163.com', pass: 'ACvXpFiLbKGbHxwG' },
        ],
      },
    ];

    emails.map((email) => {
      email.users.map((user) => {
        this.transporterPool.push({
          transporter: createTransport({
            host: email.host,
            port: email.port,
            secure: false,
            auth: {
              user: user.user,
              pass: user.pass,
            },
          }),
          user: user.user,
          useCount: 0,
        });
      });
    });
  }

  /** 初始化邮箱使用次数 */
  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async initData() {
    this.transporterPool.forEach((item) => {
      item.useCount = 0;
    });
  }

  /** 发送邮件 */
  async sendMail({ to, subject, html }: { to: string; subject: string; html: string }) {
    // 1 判断全部邮箱的使用次数都大于 200
    if (this.transporterPool.every((item) => item.useCount >= 200)) {
      throw new BadRequestException('今日注册数量已达上限，请明日申请注册');
    }
    // 2 随机一个索引
    const usePools = this.transporterPool.filter((item) => item.useCount < 200);
    const index = randomBetween(0, usePools.length - 1);
    const transporterItem = usePools[index];
    // 3 发送邮件
    try {
      await this.transporterPool[index].transporter.sendMail({
        from: { name: '股票精灵', address: this.transporterPool[index].user },
        to,
        subject,
        html,
      });
      transporterItem.useCount++;
    } catch (error) {
      throw new BadRequestException('邮件发送失败，请稍后再试');
    }
  }
}
